package com.example.retrofitdemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    Retrofit retrofit;
    Call<Reception> call;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, YouDaoActivity.class);
                startActivity(intent);
            }
        });

    }

    /**
     * 初始化Retrofit实例
     */
    private void init () {
        retrofit = new Retrofit.Builder()
                .baseUrl("xxx")     // 设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create())     //设置数据解析器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())   //支持RxJava平台
                .build();

        // 从上面看出，一个请求的URL可以通过替换块 和 请求方法 参数，来进行动态的URL更新
        // 替换块是由｛｝包裹起来的字符串构成
        // 即：Retrofit支持动态改变网络请求根目录
    }

    /**
     * 创建网络请求接口实例
     */
    private void getHttpClientInstance() {
        // 创建网络请求接口的实例
        GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
        // 发送请求进行封装
        call = request.getCall();
    }

    /**
     * 发送网络请求
     * 同步／异步
     */
    private void doHttp() throws IOException {
        // 发送网络请求（异步）
        call.enqueue(new Callback<Reception>() {
            // 网络请求成功时
            @Override
            public void onResponse(Call<Reception> call, Response<Reception> response) {
                Log.e(TAG, "onResponse result:" + response.body().toString());
                // 对结果进行处理
                handleResponse(response);
            }

            // 网络请求失败时
            @Override
            public void onFailure(Call<Reception> call, Throwable t) {
                Log.e(TAG, "onFailure: ");
            }
        });

        // 发送网络请求（同步）
        Response<Reception> response = call.execute();
        // 对结果进行处理
        handleResponse(response);

    }

    /**
     * 处理返回数据
     * @param response
     */
    private void handleResponse(Response<Reception> response) {

    }

    /**
     * 测试FormUrlEncoded
     */
    private void testFormUrlEncoded() {
        GetRequest_Interface  service = retrofit.create(GetRequest_Interface.class);
        Call<ResponseBody> call1 = service.testFromUrlEncode1("Carson", 24);
    }

    /**
     * 测试Multipart
     */
    private void testMultipart() {
        GetRequest_Interface  service = retrofit.create(GetRequest_Interface.class);
        RequestBody name = RequestBody.create(null, "Carson");
        RequestBody age = RequestBody.create(null, "24");
        RequestBody file = RequestBody.create(MediaType.parse("application/octet-stream"), "模拟内容");
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);

        Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart);
    }

    /**
     * 测试FieldMap
     */
    private void testFieldMap() {
        GetRequest_Interface  service = retrofit.create(GetRequest_Interface.class);
        Map<String, Object> map = new HashMap<>();
        map.put("username", "Carson");
        map.put("age", 24);
        Call<ResponseBody> call2 = service.testFromUrlEncode2(map);
    }
}
